package com.tt.jedis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.TimeUnit;

/**
 * @author 青青
 */
public class JedisClientPool implements JedisClient
{
    @Autowired
    private JedisPool jedisPool;

    private int index = 4;

    private Jedis selectIndex()
    {
        Jedis jedis = jedisPool.getResource();
        jedis.select(index);
        return jedis;
    }

    @Override
    public String set(String key, String value)
    {
        Jedis jedis = selectIndex();
        String result = jedis.set(key, value);
        jedis.close();
        return result;
    }

    @Override
    public String get(String key) {
        Assert.hasText(key, "Redis key 不能为空！");
        Jedis jedis = selectIndex();
        String result = jedis.get(key);
        jedis.close();
        return result;
    }

    @Override
    public Long delete(String key)
    {
        Assert.hasText(key, "redis delete key cannot null");
        Jedis jedis = selectIndex();
        Long del = jedis.del(key);
        jedis.close();
        return del;
    }

    @Override
    public Boolean exists(String key) {
        Jedis jedis = selectIndex();
        Boolean result = jedis.exists(key);
        jedis.close();
        return result;
    }

    @Override
    public String setEx(String key, int second,String value)
    {
        Jedis jedis = selectIndex();
        String setex = jedis.setex(key, second, value);
        jedis.close();
        return setex;
    }

    @Override
    public Long expire(String key, int seconds) {
        Jedis jedis = selectIndex();
        Long result = jedis.expire(key, seconds);
        jedis.close();
        return result;
    }

    @Override
    public Long ttl(String key)
    {
        Jedis jedis = selectIndex();
        Long result = jedis.ttl(key);
        jedis.close();
        return result;
    }

    @Override
    public Long incr(String key)
    {
        Jedis jedis = selectIndex();
        Long result = jedis.incr(key);
        jedis.close();
        return result;
    }

    @Override
    public Long hset(String key, String field, String value)
    {
        Jedis jedis = selectIndex();
        Long result = jedis.hset(key, field, value);
        jedis.close();
        return result;
    }

    @Override
    public String hget(String key, String field)
    {
        Jedis jedis = selectIndex();
        String result = jedis.hget(key, field);
        jedis.close();
        return result;
    }

    @Override
    public Long hdel(String key, String... field)
    {
        Jedis jedis = selectIndex();
        Long result = jedis.hdel(key, field);
        jedis.close();
        return result;
    }
}
